<template>
    <div>
        <CardBox v-for="(item, index) in cardList" :key="item.id" :title="`序号${index + 1}`" style="padding-bottom: 32px">
            <BaseButton v-if="cardList.length > 1" slot="button" type="text" color="danger" icon="el-icon-delete" @click="handleDelete(index)">
                删除
            </BaseButton>
            <el-form ref="form" :model="item" :rules="rules" size="medium" label-width="86px">
                <el-row :gutter="24">
                    <el-col :xl="6" :lg="8">
                        <el-form-item label="检查位置" prop="locationType">
                            <el-select
                                v-model="item.locationType"
                                :disabled="hasMain"
                                placeholder="请选择"
                                style="width: 100%"
                                @change="(value) => resetLocation(value, item, index)"
                            >
                                <el-option v-for="m in locationOptions" :key="m.value" :label="m.label" :value="m.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col v-if="item.locationType === 1" :xl="6" :lg="8">
                        <el-form-item label="设施名称" prop="facilityCode">
                            <!-- <FacilitySelect
                                :value.sync="item.facilityCode"
                                :all-disabled="hasMain"
                                :lng-lat.sync="item.lngLatList"
                                :params="roadInfo"
                                :name.sync="item.facilityName"
                                :props="{ value: 'id', label: 'name', multiple: true }"
                                collapse-tags
                                @change="handleChange"
                            /> -->
                            <NewFacilitySelect
                                :value.sync="item.facilityCode"
                                :disabled="hasMain"
                                :lng-lat.sync="item.lngLatList"
                                :params="{ roadCode: roadInfo.highwayCode, direction: roadInfo.direction }"
                                :name.sync="item.facilityName"
                                @change="handleChange"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col v-if="item.locationType === 2" :xl="6" :lg="8">
                        <el-col :span="14" style="padding: 0">
                            <el-form-item label="桩号" prop="stake1">
                                <el-input
                                    v-model.trim="item.stake1"
                                    :disabled="stakeDisabled"
                                    :placeholder="stakePlaceholder"
                                    maxlength="3"
                                    @change="item.stake2 = ''"
                                >
                                    <div slot="prepend" class="input-unit">K</div>
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="10" style="padding: 0">
                            <el-form-item
                                class="spe-item spe-label"
                                label-width="30px"
                                label="+"
                                prop="stake2"
                                :rules="useCheckStake(roadInfo.highwayCode, roadInfo.direction, item.stake1, roadInfo.stake)"
                            >
                                <el-input v-model.trim="item.stake2" maxlength="3" :disabled="!item.stake1 || stakeDisabled" placeholder="请输入" />
                            </el-form-item>
                        </el-col>
                    </el-col>
                    <el-col v-if="item.locationType === 3" :xl="12" :lg="16">
                        <el-col :span="7" style="padding: 0">
                            <el-form-item label="桩号范围" prop="startStake1">
                                <el-input
                                    v-model.trim="item.startStake1"
                                    :disabled="stakeDisabled"
                                    :placeholder="stakePlaceholder"
                                    maxlength="3"
                                    @change="item.startStake2 = ''"
                                >
                                    <div slot="prepend" class="input-unit">K</div>
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="5" style="padding: 0">
                            <el-form-item
                                class="spe-item spe-label"
                                label-width="30px"
                                label="+"
                                prop="startStake2"
                                :rules="useCheckStake(roadInfo.highwayCode, roadInfo.direction, item.startStake1, roadInfo.stake)"
                            >
                                <el-input v-model.trim="item.startStake2" :disabled="!item.startStake1 || stakeDisabled" maxlength="3" placeholder="请输入" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="7" style="padding: 0">
                            <el-form-item class="spe-item spe-label" label-width="50px" label="~" prop="endStake1">
                                <el-input
                                    v-model.trim="item.endStake1"
                                    :disabled="stakeDisabled"
                                    :placeholder="stakePlaceholder"
                                    maxlength="3"
                                    @change="item.endStake2 = ''"
                                >
                                    <div slot="prepend" class="input-unit">K</div>
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="5" style="padding: 0">
                            <el-form-item
                                class="spe-item spe-label"
                                label-width="30px"
                                label="+"
                                prop="endStake2"
                                :rules="useCheckStake(roadInfo.highwayCode, roadInfo.direction, item.endStake1, roadInfo.stake)"
                            >
                                <el-input v-model.trim="item.endStake2" maxlength="3" :disabled="!item.endStake1 || stakeDisabled" placeholder="请输入" />
                            </el-form-item>
                        </el-col>
                    </el-col>

                    <el-col :xl="6" :lg="8">
                        <el-form-item label="" prop="locationDescription">
                            <el-input v-model.trim="item.locationDescription" maxlength="20" show-word-limit placeholder="请输入位置补充描述" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="检查情况" prop="inspectionResult">
                            <el-input
                                v-model.trim="item.inspectionResult"
                                style="width: 100%"
                                placeholder="请输入"
                                clearable
                                type="textarea"
                                maxlength="200"
                                show-word-limit
                                :autosize="{ minRows: 6, maxRows: 10 }"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="整改情况" prop="rectificationResult">
                            <el-input
                                v-model.trim="item.rectificationResult"
                                style="width: 100%"
                                placeholder="请输入"
                                clearable
                                type="textarea"
                                maxlength="200"
                                show-word-limit
                                :autosize="{ minRows: 6, maxRows: 10 }"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="上传图片">
                            <ImageUploadNew ref="imageUpload" :list.sync="item.photosArr"></ImageUploadNew>
                        </el-form-item>
                    </el-col>
                    <el-col v-for="(m, i) in item.photosArr" :key="m.uid" :span="24">
                        <el-form-item :label="`图片${i+1}说明`">
                            <el-input v-model.trim="item.photosArr[i].picDesc" maxlength="100" show-word-limit clearable placeholder="请输入" />
                        </el-form-item>
                    </el-col>
                    <!-- 机电设备选中列表 -->
                    <el-col v-if="item.locationType === 4" :span="24">
                        <el-form-item label="设备信息" prop="content">
                            <DevicesSelectTable :list.sync="item.deviceList" :params="{ ...roadInfo, direction: roadInfo.directionName }"></DevicesSelectTable>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </CardBox>

        <div v-if="!hasMain" class="add-btn" @click="handleAdd">添加巡查点</div>
    </div>
</template>

<script>
import { DirectionOptions } from '@/config/constants'
import { uniqueId } from 'lodash-es'
import useCheckStake from '@/hooks/useCheckStake'
import { LocationOptions } from '@/views/maintenance-decision/constants'
import { isInteger } from '@/utils/validate'
import DevicesSelectTable from './DevicesSelectTable.vue'
import reconfirm from '@/utils/reconfirm'

export default {
    name: 'CulvertCardList',
    components: {
        DevicesSelectTable
    },
    props: {
        hasMain: {
            type: Boolean,
            default: false
        },
        mainInfo: {
            type: Array,
            default: () => []
        },
        roadInfo: {
            type: Object,
            default: () => {}
        }
    },
    data() {
        return {
            locationOptions: LocationOptions,
            directionOptions: DirectionOptions,
            culvertTypeOptions: [
                { fid: 1, name: '类型1' },
                { fid: 2, name: '类型2' }
            ],
            cardList: [
                {
                    fid: uniqueId(),
                    locationType: '',
                    content: [],
                    facilityCode: [],
                    locationDescription: '',
                    stake1: '',
                    stake2: '',
                    startStake1: '',
                    startStake2: '',
                    endStake1: '',
                    endStake2: '',
                    photosArr: []
                }
            ],
            form: {},
            rules: {
                facilityCode: [{ required: true, message: '请选择设施名称', trigger: 'change' }],
                locationType: [{ required: true, message: '请选择检查位置', trigger: 'change' }],
                inspectionResult: [{ required: true, message: '请输入检查情况', trigger: 'blur' }],
                rectificationResult: [{ required: true, message: '请输入整改情况', trigger: 'blur' }],
                stake1: [
                    { required: true, message: '请输入桩号', trigger: 'blur' },
                    { required: true, validator: this.validNum, trigger: 'blur' }
                ],
                startStake1: [
                    { required: true, message: '请输入起始桩号', trigger: 'blur' },
                    { required: true, validator: this.validNum, trigger: 'blur' }
                ],
                endStake1: [
                    { required: true, message: '请输入终点桩号', trigger: 'blur' },
                    { required: true, validator: this.validNum, trigger: 'blur' }
                ]
            },
            currentIndex: 0
        }
    },
    computed: {
        // 如果路段code和方向一个不存在，或者是关联养护工程的，都禁止
        stakeDisabled() {
            const road = this.roadInfo.highwayCode
            const direction = this.roadInfo.direction
            return !direction || !road || this.hasMain
        },
        stakePlaceholder() {
            const placeholder = this.stakeDisabled ? '请先选择路线名称和方向' : '请输入'
            return placeholder
        }
    },
    watch: {
        mainInfo: {
            // immediate: true,
            deep: true,
            handler(newVal) {
                if (newVal.length > 0) {
                    this.cardList = newVal
                } else {
                    this.cardList = [
                        {
                            fid: uniqueId(),
                            locationType: '',
                            content: [],
                            facilityCode: [],
                            locationDescription: '',
                            stake1: '',
                            stake2: '',
                            startStake1: '',
                            startStake2: '',
                            endStake1: '',
                            endStake2: '',
                            photosArr: []
                        }
                    ]

                    this.$nextTick(() => {
                        this.$refs.form[0].clearValidate()
                    })
                }
            }
        },
        hasMain(newVal) {
            // 如果没有关联养护工程，置空
            if (!newVal) {
                this.cardList = [
                    {
                        fid: uniqueId(),
                        locationType: '',
                        content: [],
                        facilityCode: [],
                        locationDescription: '',
                        stake1: '',
                        stake2: '',
                        startStake1: '',
                        startStake2: '',
                        endStake1: '',
                        endStake2: '',
                        photosArr: []
                    }
                ]
            }
        }
    },
    methods: {
        handleDelete(index) {
            reconfirm({
                isPromise: false,
                callback: () => {
                    this.cardList.splice(index, 1)
                }
            })
        },
        handleChange(val) {
            console.log(this.cardList)
        },
        validNum(rule, value, callback) {
            if (value && !isInteger(value)) {
                callback(new Error('请输入数字'))
            } else {
                callback()
            }
        },

        handleValidate() {
            return new Promise((resolve, reject) => {
                const list = []
                const validas = []
                this.$refs['form'].forEach((item, index) => {
                    list.push(
                        new Promise((resolve) => {
                            item.validate((valida) => {
                                validas.push(valida)
                                resolve()
                            })
                        })
                    )
                })
                Promise.all([...list])
                    .then(() => {
                        const res = !validas.some((item) => item === false)
                        resolve(res)
                    })
                    .catch((err) => {
                        reject(err)
                    })
            })
        },
        handleAdd() {
            this.cardList.push({
                fid: uniqueId(),
                locationType: '',
                content: [],
                facilityCode: [],
                locationDescription: '',
                stake1: '',
                stake2: '',
                startStake1: '',
                startStake2: '',
                endStake1: '',
                endStake2: '',
                photosArr: []
            })
            console.log(this.cardList)
        },
        getData() {
            this.cardList.forEach((item, index) => {
                this.cardList[index].photosArray = (item.photosArr || []).map(m => {
                    return {
                        picName: m.name,
                        url: m.response.data.objectUrl,
                        picDesc: m.picDesc
                    }
                })
                delete item.photosArr
                // 根据位置类型单独处理对应字段
                console.log(item.locationType)
                switch (item.locationType) {
                    case 1:
                        item.name = item.facilityName
                        // [[1,'aaa'], [2,'bb']] 转为'1/aaa,2/bbb'
                        // item.code = item.facilityCode.map((item) => item.join('/')).toString()
                        item.code = item.facilityCode.toString()
                        break
                    case 2:
                        item.stake = `K${item.stake1}+${item.stake2}`
                        break
                    case 3:
                        item.stake = `K${item.startStake1}+${item.startStake2}~K${item.endStake1}+${item.endStake2}`
                        break
                    case 4:
                        item.content = item.deviceList
                        break
                    default:
                        item.name = ''
                        item.code = ''
                        item.content = []
                        break
                }
            })
            return this.cardList
        },
        resetLocation(val, item, index) {
            // 对应form验证清除，值清空，验证不清除会导致验证信息错位
            this.$refs['form'][index].clearValidate([
                'startStake1',
                'startStake2',
                'endStake1',
                'endStake2',
                'stake1',
                'stake2',
                'locationDescription',
                'inspectionResult',
                'rectificationResult'
            ])
            item.startStake1 = ''
            item.startStake2 = ''
            item.endStake1 = ''
            item.endStake2 = ''
            item.stake1 = ''
            item.stake2 = ''
        },
        useCheckStake
    }
}
</script>

<style lang="scss" scoped>
.spe-item {
    ::v-deep {
        .el-form-item__label {
            text-align: center;
            padding: 0;
            &::before {
                display: none;
            }
        }
        .el-input,
        .el-input__inner {
            min-width: auto !important;
        }
    }
}

.add-btn {
    width: 100%;
    height: 64px;
    margin-top: 32px;
    background-color: #fff;
    border: 2px dotted rgb(217, 217, 217);
    border-radius: 5px;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
}
</style>
